#!/usr/bin/env python
# -*- coding:utf-8 -*-
#Boa:App:BoaApp

import time
import os
import sys
import json
import threading

import wx
import pyWinhook
import pythoncom

import Frame1


modules = {'Frame1': [1, 'Main frame of Application', u'Frame1.py']}


class BoaApp(wx.App):
    """与__init__()方法类似

        wxPython中所有，可能不适合其他一些库。
        OnInit()方法在应用程序开始时并在主事件循环开始前被wxPython系统调用。
        这个方法不要求参数并返回一个布尔值,如果所返回的值是False,则应用程序将立即退出。
    """
    def OnInit(self):
        self.main = Frame1.create(None)
        # 展示界面
        self.main.Show()
        # 将wx.App类所派生出来的BoaApp类通过OnInit方法所创建的框架置于顶层, 即作为parent window
        # Set the “main” top level window, which will be used for the parent of the on-demand output window as well as for dialogs that do not have an explicit parent set.
        self.SetTopWindow(self.main)
        return True


# 执行代码
def main():
    # 添加
    application = BoaApp(0)
    # Execute the main GUI event loop
    application.MainLoop()



def single_run(script_path, run_times=1):

    t = HookThread()
    t.start()

    try:
        j = 0
        while j < run_times or run_times == 0:
            j += 1
            print('===========', j, '==============')
            Frame1.RunScriptClass.run_script_once(script_path, j)
        print('script run finish!')
    except Exception as e:
        raise e
    finally:
        os._exit(0)


class HookThread(threading.Thread):

    def run(self):

        def on_keyboard_event(event):
            key_name = event.Key.lower()
            stop_name = 'f9'
            if key_name == stop_name:
                print('break exit!')
                os._exit(0)
            return True

        hm = pyWinhook.HookManager()
        hm.KeyAll = on_keyboard_event
        hm.HookKeyboard()
        pythoncom.PumpMessages()


if __name__ == '__main__':

    # 最开始执行的代码, 并且初始长度只为1, 且为路径该文件所在路径
    print(sys.argv)

    # 以参数模式启动程序执行if之后的代码
    if len(sys.argv) > 1:
        script_path = sys.argv[1]
        run_times = int(sys.argv[2]) if len(sys.argv) > 2 else 1
        single_run(script_path, run_times)
    else:
        main()

